package org.fxd.zweixin.busi_login.login.service;

import java.util.List;
import java.util.Map;

import org.fxd.zweixin.busi_login.login.domain.dto.ForgetPwdDTO;
import org.fxd.zweixin.busi_login.login.domain.dto.LoginDTO;
import org.fxd.zweixin.busi_system.user.domian.po.t_user;
import org.fxd.zweixin.util.SessionTool;
import org.fxd.zweixin.util.WebTools;
import org.springframework.stereotype.Service;
import org.tmsps.ne4spring.base.BaseService;
import org.tmsps.ne4spring.utils.ChkUtil;

import com.alibaba.fastjson.JSONObject;

@Service
public class LoginService extends BaseService {

	public JSONObject login(LoginDTO loginDTO) {
		// TODO 登录
		JSONObject result = new JSONObject();
		t_user user = this.findByUname(loginDTO.getUname());
		if (ChkUtil.isNull(user)) {
			result.put("login", false);
			result.put("msg", "登录失败，该用户不存在");
			return result;
		}
		user = this.findByUnameAndPassword(loginDTO);
		if (ChkUtil.isNull(user)) {
			result.put("login", false);
			result.put("msg", "登录失败，用户名或密码错误");
			return result;
		}
		String userKey = SessionTool.setSessionLoginKey(user.getKid());
		result.put("cookie", userKey);
		result.put("login", true);
		result.put("msg", "登录成功");
		return result;
	}

	public boolean check_mobile(String uname) {
		String sql = "select * from t_user t where (t.uname=?) and status=0 ";
		List<Map<String, Object>> list = bs.findList(sql, uname);
		if (ChkUtil.isNull(list)) {
			return true;
		}
		return false;
	}

	public t_user findByCode(String code) {
		String sql = "select t.* from t_user t where t.status=0 and (t.self_invent_code=?) ";
		t_user user = bs.findObj(t_user.class, sql, code);
		return user;
	}

	private t_user findByUnameAndPassword(LoginDTO loginDTO) {
		// TODO 通过用户名和密码获取对象
		String sql = "select * from t_user t where t.status=0 and (t.uname=?) and (t.pwd=?)";
		return bs.findObj(t_user.class, sql, loginDTO.getUname(), loginDTO.getPassword());
	}

	private t_user findByUname(String uname) {
		// TODO 通过用户名获取对象
		String sql = "select * from t_user t where t.status=0 and (t.uname=?)";
		return bs.findObj(t_user.class, sql, uname);
	}

	public JSONObject forgetPwd(ForgetPwdDTO forgetPwdDTO) {
		// TODO 忘记密码保存
		JSONObject result = new JSONObject();
		Object m = WebTools.getSession().getAttribute(forgetPwdDTO.getUname());
		if (ChkUtil.isNull(m)) {
			result.put("check", false);
			result.put("msg", "请先发送验证码!");
		} else if (!m.equals(forgetPwdDTO.getCode())) {
			result.put("check", false);
			result.put("msg", "验证码错误！");
		} else {
			t_user user = this.findByUname(forgetPwdDTO.getUname());
			user.setPwd(forgetPwdDTO.getPassword());
			bs.updateObj(user);
			
			result.put("check", true);
			result.put("msg", "密码修改成功");
		}
		return result;
	}
}
